<template>
  <el-dialog title="流程权限配置" :visible.sync="open" width="70%" :before-close="close" custom-class="userModel"
    :append-to-body="true">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24" style="border-right: 1px solid #f0f0f0">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="10" :xs="24">
        <el-table v-loading="loading" :data="userList" border size="mini" ref="tableRef"
          @select="handleSelectionChange" row-key="userId" @select-all="handleSelectionChange">
          <el-table-column type="selection" :reserve-selection="true" width="55" align="center">
          </el-table-column>
          <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
          <el-table-column label="姓名" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
          <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" :show-overflow-tooltip="true" />
        </el-table>

        <div style="display: flex; justify-content: flex-end">
          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      </el-col>
      <el-col :span="10" :xs="24">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>已选（<span style="color: red; font-size: 12px">若不选择代表全部用户拥有该流程权限</span>）</span>
          </div>
          <!--流程处理表单模块-->
          <el-col :span="24" style="margin-bottom: 20px">
            <el-empty description="暂无数据" v-show="!viewArr.length"></el-empty>

            <div v-if="viewArr.length">
              <div v-for="(item, index) in viewArr" :key="item.userId" style="
                  display: flex;
                  justify-content: space-between;
                  border: 1px solid #d9d9d9;
                  align-items: center;
                  padding: 5px 20px;
                  margin-top: 15px;
                  border-radius: 6px;
                ">
                <div>
                  <span>{{ index + 1 }}</span>
                  <span style="margin-left: 10px">{{ item.nickName }}
                  </span>
                </div>
                <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(item.userId)" style="
                    height: 26px;
                    width: 26px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                  "></el-button>
              </div>
            </div>
          </el-col>
        </el-card>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer" style="display: flex; justify-content: flex-end">
      <div>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="btnLoading">确 定</el-button>
      </div>
    </span>
  </el-dialog>
</template>

<script>
import { deptTreeSelect, listUser } from "@/api/system/user.js";
import pagination from "@/components/Pagination/index";
import {
  appProcessStartRole,
  getAppProcessStartRole,
} from "@/api/workflow/model.js";
export default {
  props: {
    open: {
      type: Boolean,
      default: false,
    },
    close: {
      type: Function,
      default: () => { },
    },
    row: {
      type: Object,
      default: () => { },
    },
  },
  components: {
    pagination,
  },
  data() {
    return {
      btnLoading: false,
      selectionArr: [],
      loading: false,
      userList: [],
      total: 0,
      deptName: undefined,
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: "0",
        deptId: undefined,
      },
      userIds: [],
      userName:[],
      viewArr: []
    };
  },
  watch: {
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    async handleSubmit() {
      if (!this.selectionArr?.length) {
        this.close();
        return;
      }
      const ids = [];
      this.selectionArr?.forEach((item) => {
        ids.push(item.userId);
      });
      if (ids.length) {
        this.btnLoading = true;
        const res = await appProcessStartRole({
          processKey: this.row?.modelKey,
          userId: ids.toString(),
        });
        if (res.code === 200) {
          this.$message.success("设置成功！");
          this.close();
        } else {
          this.$message.error(res.msg);
        }
        this.btnLoading = false;
      }
    },
    async getRoleList() {
      const res = await getAppProcessStartRole({
        processKey: this.row.modelKey,
      });
      if (res.code === 200) {
        if (!!res.rows[0]?.userId) {
          this.userIds = res.rows[0]?.userId?.split(",");
          this.userName = res.rows[0]?.userName?.split(",");
          this.userIds.forEach((item,index)=>{
            this.viewArr.push({ userId: item, nickName: this.userName[index] })
          })
        }
      } else {
        this.$message.error(res.msg);
      }
    },
    handleSelectionChange(arr) {
      this.selectionArr = arr;
      let viewArr = []
      arr.forEach(item => {
        viewArr.push({ userId: item.userId, nickName: item.nickName })
      })
      this.viewArr = viewArr
    },
    handleDelete(id) {
      const row = this.selectionArr.filter((item) => item.userId === id);
      this.selectionArr = this.selectionArr.filter(
        (item) => item.userId !== id
      );
      const _this = this;
      this.$nextTick(() => {
        _this.$refs.tableRef.toggleRowSelection(row?.[0], false);
      });
      this.viewArr = this.viewArr.filter(
        (item) => item.userId !== id
      );
    },
    getList() {
      this.loading = true;
      const _this = this;
      listUser({ ...this.queryParams, userType: "front_user" }).then(
        (response) => {
          this.userList = response.rows;
          this.total = response.total;

          this.$nextTick(() => {
            _this.userList?.forEach((item, index) => {
              if (_this.userIds?.includes(String(item.userId))) {
                _this.$refs.tableRef.toggleRowSelection(item, true);
              }
              if (index === _this.userList.length) {
                _this.userIds = [];
              }
            });
          });
          this.loading = false;
        }
      );
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
  },
  async created() {
    await this.getRoleList();
    this.getList();
    this.getDeptTree();
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-row {
  border: none !important;
}

::v-deep .el-col {
  height: 400px;
  overflow-y: scroll;
}
</style>